package com.demo.gateway.mapping;

/**
 * @author yzy
 * @date 2024/7/15 下午11:41
 */
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

public class JsonTraversalExample2 {

    public static void main(String[] args) throws IOException {
        String s = "E:\\codes\\javacode\\gateway\\src\\main\\resources\\conf\\channel\\demo\\targetJson.json";

        String json = FileUtils.readFileToString(new File(s), "UTF-8");
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();

        // 解析 JSON 字符串为 JsonNode
        JsonNode rootNode = objectMapper.readTree(json);

        // 读取映射配置
        HashMap<String, String> map = readPropertiesToMap();

        // 调用递归遍历方法
        JsonNode newRootNode = traverseAndModifyJson("", rootNode, map, objectMapper);

        // 输出修改后的 JSON
        System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(newRootNode));
    }

    public static HashMap<String, String> readPropertiesToMap() {
        try {
            Properties properties = new Properties();
            HashMap<String, String> map = new HashMap<>();
            FileInputStream fileInputStream = new FileInputStream(new File("E:\\codes\\javacode\\gateway\\src\\main\\resources\\conf\\channel\\demo\\mapping.properties"));
            properties.load(fileInputStream);
            properties.forEach((k, v) -> {
                map.put(k.toString(), v.toString());
            });
            return map;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 递归遍历 JsonNode 并修改 key 的方法
    private static JsonNode traverseAndModifyJson(String prefix, JsonNode node, HashMap<String, String> map, ObjectMapper objectMapper) {
        if (node.isObject()) {
            ObjectNode newObjectNode = objectMapper.createObjectNode();
            node.fields().forEachRemaining(entry -> {
                String key = prefix.isEmpty() ? entry.getKey() : prefix + "." + entry.getKey();
                String newKey = map.getOrDefault(key, entry.getKey());
                newObjectNode.set(newKey, traverseAndModifyJson(key, entry.getValue(), map, objectMapper));
            });
            return newObjectNode;
        } else if (node.isArray()) {
            for (int i = 0; i < node.size(); i++) {
                ((ObjectNode) node).set(i + "", traverseAndModifyJson(prefix, node.get(i), map, objectMapper));
            }
        }
        return node;
    }
}
